package com.ljy.tkmodel.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljy.tkmodel.entity.Room;
import com.ljy.tkmodel.entity.vo.RoomConditionVo;
import com.ljy.tkmodel.job.RoomJob;
import com.ljy.tkmodel.mapper.RoomMapper;
import com.ljy.tkmodel.service.RoomService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljy.tkmodel.util.PageUtils;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import lombok.val;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.quartz.SimpleScheduleBuilder.simpleSchedule;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-03-08
 */
@Log4j2
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements RoomService {
    @Autowired
    RoomMapper roomMapper;
//    @Autowired
//    Scheduler scheduler;
    @Override
    public int noXMLInsert(Room room) {
        if (!ObjectUtils.isEmpty(room)) {
            return baseMapper.insert(room);
        }
        return 0;
    }

    @Override
    public List<Room> optimizeConditionQuery(HashMap<String, Object> map) {
        QueryWrapper<Room> queryWrapper = new QueryWrapper<>();

        Integer peoples = (Integer) map.get("galleryful");
        if (peoples != null) {
            queryWrapper.le("galleryful", peoples);
        }

        if (map.get("room_state") != null) {
            boolean room_state = (boolean) map.get("room_state");
            if (!room_state) {
                queryWrapper.eq("room_state", room_state);
            }
        }
        queryWrapper.orderByAsc("galleryful");
        if (map.get("page") != null && map.get("limit") != null) {
            Page<Room> page = new Page<>(Long.valueOf((String) map.get("page")), Long.valueOf((String) map.get("limit")));
            baseMapper.selectPage(page, queryWrapper);
            return page.getRecords();
        }
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public boolean insertSql(Room room) {

        //仿照mybatisplus 生成雪花id
        Snowflake snowflake = IdUtil.getSnowflake();
        String idStr = snowflake.nextIdStr();
        room.setId(idStr);
        //创建更新时间
//        long createAndUpdateDate = new Date().getTime() / 1000;
//        room.setCreateTime(createAndUpdateDate);
//        room.setUpdateTime(createAndUpdateDate);
        //是否删除
//        room.setIsDel(false);
        return roomMapper.insertSql(room);
    }

    @Override
    public int SchoolCurriculum(RoomConditionVo roomConditionVo) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("galleryful", roomConditionVo.getPeoples());
        map.put("room_state", false);
        //查询是否有可用的教师
        List<Room> list = optimizeConditionQuery(map);
        if (!CollectionUtils.isEmpty(list)) {
            //组装
            Room room = list.get(0);
            room.setStartDate(room.getStartDate());
            room.setEndDate(roomConditionVo.getEndDate());
            room.setTid(roomConditionVo.getTid());
            return baseMapper.updateById(room);
        } else {
            log.warn("当前没有可用教室，请稍后重试！");
            return 0;
        }
    }

    @Override
    public void putRoomScheduler() {
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("room_state", false);
//        List<Room> roomList = optimizeConditionQuery(map);
//        for (Room r:roomList) {
//            //设置与定时任务里面交互的数据
//            JobDetail jobDetail = JobBuilder.newJob(RoomJob.class)
//                    .usingJobData("id",r.getId())
//                    .usingJobData("startDate",r.getStartDate())
//                    .build();
//            //创建定时任务触发器
//            SimpleTrigger simpleTrigger = (SimpleTrigger)TriggerBuilder.newTrigger()
//                    .forJob(jobDetail)
//                    .startAt(new Date((r.getStartDate()-3600)*1000))
//                    .build();
//            try {
//                scheduler.scheduleJob(jobDetail,simpleTrigger);
//            } catch (SchedulerException e) {
//                e.printStackTrace();
//            }
//        }
    }

    @SneakyThrows
    @Override
    public void putRoomSchedulerTest() {
//        //创建一个scheduler
//        //Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
//        scheduler.getContext().put("skey", "svalue");
//
//        //创建一个Trigger
//        Trigger trigger = TriggerBuilder.newTrigger()
//                .withIdentity("trigger1", "group1")
//                .usingJobData("t1", "tv1")
//                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3)
//                        .repeatForever()).build();
//        trigger.getJobDataMap().put("t2", "tv2");
//
//        //创建一个job
//        JobDetail job = JobBuilder.newJob(RoomJob.class)
//                .usingJobData("j1", "jv1")
//                .withIdentity("myjob", "mygroup").build();
//        job.getJobDataMap().put("j2", "jv2");
//
//        //注册trigger并启动scheduler
//        scheduler.scheduleJob(job,trigger);
//        scheduler.start();
    }
}
